<?php
define('mcz_CLI_MODE', true);

function walk_dir( $root, $callback, $recursive = true )
{
    $root = realpath($root);
    $dh   = @opendir( $root );
    if( false === $dh )
    {
        return false;
    }
    while(false !==  ($file = readdir($dh)))
    {
        if( "." == $file || ".." == $file )
        {
            continue;
        }
        call_user_func( $callback, "{$root}/{$file}" );
        if( false !== $recursive && is_dir( "{$root}/{$file}" ))
        {
            walk_dir( "{$root}/{$file}", $callback, $recursive );
        }
    }
    closedir($dh);
    return true;
}

function importTune($tunePath)
{
    if(!is_file($tunePath))
    {
        return;
    }
    $pathinfos = pathinfo($tunePath);
    $infos = mcz_AudioTags::read($tunePath);
    if(!$infos)
    {
        echo("\n" . $pathinfos['basename'] . ': ' . T('Unsupported format.'));
        return;
    }
    if(empty($infos['artist']) or empty($infos['title']))
    {
        echo("\n" . $pathinfos['basename'] . ': ' . T('Not enough tag information.'));
        return;
    }
    if(empty($infos['album']))
    {
        $infos['album'] = 'unknown';
    }
    $newFileName =         mcz_TUNES_DIR . '/' .
        substr(mcz_Inflector::fileName($infos['artist']), 0, 1) . '/' .
        mcz_Inflector::fileName($infos['artist']) . '/' .
        mcz_Inflector::fileName($infos['album']) . '/' .
        mcz_Inflector::fileName($infos['title']);

    if(is_file($newFileName . '.' . $pathinfos['extension']))
    {
       if(md5_file($newFileName . '.' . $pathinfos['extension']) == md5_file($tunePath))
       {
            echo("\n" . $pathinfos['basename'] . ': ' . T('already exists.'));
            return;
       }
       $i = 1;
       $tmpName = $newFileName . '_' . $i;
       while(is_file($tmpName . '.' . $pathinfos['extension']))
       {
            $i++;
            $tmpName .= $newFileName . '_' . $i;
       }
       $newFileName = $tmpName . '.' . $pathinfos['extension'];
    }
    else
    {
        $newFileName .= '.' . $pathinfos['extension'];
    }

    //echo("\n" . substr($newFileName, strlen(mcz_TUNES_DIR)));
    //return;

    $newDir = dirname($newFileName);
    if(!is_dir($newDir))
    {
        mkdir($newDir, 0777, true);
    }

    if(rename($tunePath, $newFileName))
    {
        chmod($newFileName, 0755);
        $tune = new mcz_Tune();
        $tune->path    = substr($newFileName, strlen(mcz_TUNES_DIR));
        $tune->artist  = $infos['artist'];
        $tune->title   = $infos['title'];
        $tune->album   = $infos['album'];
        $tune->track   = $infos['track'];
        $tune->genre   = $infos['genre'];
        $tune->comment = $infos['comment'];
        $tune->time    = $infos['time'];
        try
        {
            $tune->save();
            echo("\n" . $pathinfos['basename'] . ': ' . T('Imported.'));
            return;
        }
        catch(Exception $e)
        {
            echo("\n" . $pathinfos['basename'] . ': ' . T('Exception occured: ')
                 . $e->getMessage());
        }
    }
    echo("\n" . $pathinfos['basename'] . ': ' . T('Could not import tune.'));
    return;
}

function addTune($tunePath, $updateExistingTune = false)
{
    if(!is_file($tunePath))
    {
        return;
    }
    $basename = basename($tunePath);
    $path = substr($tunePath,strlen(mcz_TUNES_DIR));
    $tune = mcz_Tune::findOneByPath($path);
    if($tune)
    {
        if($tune->file_modified == filemtime($tunePath))
        {
            echo("\n" . $basename . ': ' . T('Skipping existing tune.'));
            return;
        }
    }

    $infos = mcz_AudioTags::read($tunePath);
    if(!$infos)
    {
        echo("\n" . $basename . ': ' . T('Unsupported format.'));
        return;
    }

    $artist = trim($infos['artist']);
    $title  = trim($infos['title']);
    if(!empty($artist) and !empty($title))
    {
        if(!$tune)
        {
            echo("\n" . $basename . ': ' . T('Adding new tune.'));
            $tune = new mcz_Tune();
            $tune->path = $path;
        }
        else
        {
            echo("\n" . $basename . ': ' . T('Updating existing tune.'));
        }

        $tune->artist  = $infos['artist'];
        $tune->title   = $infos['title'];
        $tune->album   = $infos['album'];
        $tune->track   = $infos['track'];
        $tune->genre   = $infos['genre'];
        $tune->comment = $infos['comment'];
        $tune->time    = $infos['time'];
        try
        {
            $tune->save();
        }
        catch(Exception $e)
        {
            echo("\n" . $basename . ': ' .
                 T('An exception occured while saving: ') . $e->getMessage());
        }
    }
    else
    {
        echo("\n" . $basename . ': ' . T('Not enough infos.'));
    }

    return;
}


function crawl($url)
{
    preg_match_all('/href="([^"].+?)"/', file_get_contents($url), $matches);
    $tmpfile = dirname(__FILE__) . '/tmp.mp3';
    foreach($matches[1] as $match)
    {
        if(substr($match, -3) == 'mp3')
        {
            if(copy($match,$tmpfile))
            {
                print_r(mcz_AudioTags::read($tmpfile));
            }
        }
    }
}

require(realpath(dirname(__FILE__) . '/../../index.php'));

restore_error_handler();

if(!isset($argv[1]))
{
    die("Missing argument.\n");
}

switch($argv[1])
{
    case 'addnew':
        walk_dir(mcz_TUNES_DIR, 'addTune');
        break;
    case 'import':
        walk_dir(mcz_IMPORT_DIR, 'importTune');
        break;
    case 'search':
        $res = mcz_Tune::search($argv[2]);
        foreach($res['items'] as $item)
        {
            echo($item->artist . ': ' . $item->title . "\n");
        }
        break;
    case 'analyze':
        $words = mcz_Analyzer::analyze($argv[2]);
        $res = array();
        foreach($words as $word)
        {
            $res[$word] = metaphone($word);
        }
        print_r($res);
        break;
    case 'crawl':
        crawl($argv[2]);
        break;
    default:
        break;
}
echo("\n");
echo mcz_Benchmark::cliReport();